package com.chang.bootplus.base.utils;
import java.lang.String;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.entity.UserResultmap;
import com.chang.bootplus.mapper.BmiMapper;
import com.chang.bootplus.mapper.UserResultmapMapper;
import com.chang.bootplus.po.CalculatePO;
import com.chang.bootplus.service.UserResultmapService;
import com.chang.bootplus.vo.CalculateVO;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static java.math.BigDecimal.ROUND_DOWN;
import static java.math.RoundingMode.HALF_DOWN;

@Data
@Component
public class EvaulateMap {

    private  Integer otherScore;

    public  HashMap<Integer,HashMap<Integer, List>> maxMap=new HashMap<>();

    @Resource
    BmiMapper bmiMapper;

    public EvaulateMap(Integer otherScore) {
        // 1 表示男 0表示女 String 表示项目id
        HashMap<Integer,List> map1 = new HashMap<>();
        map1.put(1, Arrays.asList(1700	,2000	,2300	,2600	,2900	,3200));
        map1.put(0, Arrays.asList(1400	,1600	,1800	,2000	,2250	,2500));
        maxMap.put(1,map1);

        HashMap<Integer,List> map2 = new HashMap<>();
        map2.put(1, Arrays.asList(10.2	,9.6	,9.1	,8.7	,8.4	,8.2));
        map2.put(0, Arrays.asList(11.0	,10.0	,9.2	,8.7	,8.3	,8.2));
        maxMap.put(2,map2);

        HashMap<Integer,List> map3 = new HashMap<>();
        map3.put(1, Arrays.asList(16.1	,16.2,	16.3,	16.4,	16.5,	16.6));
        map3.put(0, Arrays.asList(18.6	,18.9,	19.2,	19.5,	19.8,	19.9));
        maxMap.put(3,map3);

        HashMap<Integer,List> map4 = new HashMap<>();
        map4.put(1, Arrays.asList(109	,117,	126,	137,	148,	157));
        map4.put(0, Arrays.asList(117	,127,	139,	149,	158,	166));
        maxMap.put(4,map4);

        HashMap<Integer,List> map5 = new HashMap<>();
        map5.put(1, Arrays.asList(null,null,48	,49,	50,	51));
        map5.put(0, Arrays.asList(null,null,46	,47,	48,	49));
        maxMap.put(5,map5);

        HashMap<Integer,List> map6 = new HashMap<>();
        map6.put(1, Arrays.asList(null,null,null,null,1.36	,1.30));
        map6.put(0, Arrays.asList(null,null,null,null,1.41	,1.37));
        maxMap.put(6,map6);
    }

    @Resource
    UserResultmapMapper userResultmapMapper;

    @Autowired
    UserResultmapService userResultmapService;

    public static  EvaulateMap evaulateMap;

    @PostConstruct
    public void init(){
        evaulateMap=this;
        evaulateMap.bmiMapper=this.bmiMapper;
        evaulateMap.userResultmapService=this.userResultmapService;
        evaulateMap.userResultmapMapper=this.userResultmapMapper;

    }


    //获得最好成绩
    public static Double getTopValueById(Integer projectId,Integer classId,Integer sex) {
        UserResultmap one = evaulateMap.userResultmapService.getOne(new LambdaQueryWrapper<UserResultmap>().eq(UserResultmap::getLevelValue, 1).eq(UserResultmap::getProjectId, projectId).eq(UserResultmap::getGradeNum, classId).eq(UserResultmap::getSex, sex));
        return one.getMaxValue();
    }

    public CalculateVO calculate(CalculatePO po, UserResultmap userResultmap) {
        Double topValue = EvaulateMap.getTopValueById(po.getProjectId(), po.getClassId(), po.getSex());
        if (userResultmap==null&&po.getResult()>topValue){
            Integer ans=100;
            CalculateVO calculateVO=new CalculateVO();
            if (po.getProjectId()==4){
                Integer other=po.getResult().intValue()-topValue.intValue();
                ans+=(other/2)>20 ? 20: (other/2);
                otherScore=(other/2)>20 ? 20: (other/2);
                System.out.println("=========================================================================="+otherScore);
                calculateVO = new CalculateVO().setScore(ans).setLevel("优秀");
            }else {
                calculateVO = new CalculateVO().setScore(ans).setLevel("优秀");
            }
            return   calculateVO;
        }else if (userResultmap==null&&po.getResult()<topValue){
            CalculateVO calculateVO = new CalculateVO().setScore(0).setLevel("不及格");
            return  calculateVO;
        }
        Double minValue = userResultmap.getMinValue();
        Double maxValue = userResultmap.getMaxValue();
        Double proDifference = userResultmap.getProDifference();
        Integer baseValue = userResultmap.getBaseValue();
        Integer bestValue = userResultmap.getBestValue();
        Integer valDifference = userResultmap.getValDifference();
        Integer ans=0;
        if (!po.getResult().equals(maxValue)){
            // 基础分+ 当前分与最低分距离除以成绩间距的商再乘以分间距
            BigDecimal bd1 = new BigDecimal(Double.toString(po.getResult()));
            BigDecimal bd2 = new BigDecimal(Double.toString(minValue));
            BigDecimal bd3 = new BigDecimal(Double.toString(proDifference));
//        double v2=bd1.subtract(bd2).divide(bd3).doubleValue();
            // 除完后向下取整
            int i = bd1.subtract(bd2).divide(bd3, ROUND_DOWN).intValue();
             ans=Double.valueOf(baseValue+ i *valDifference).intValue();
        }else {
             ans=bestValue;
        }

        if (po.getProjectId()==4&&ans>=100){
            ans=100;
            Integer topValueById = topValue.intValue();
            Integer other=po.getResult().intValue()-topValueById;
            ans+=(other/2)>20 ? 20: (other/2);
            otherScore=(other/2)>20 ? 20: (other/2);
            System.out.println("=========================================================================="+otherScore);
        }else if (po.getProjectId()!=4&&ans>=100){
            ans=100;
        }else {
            ans= ans>120 ? 120: ans;
        }
        String level = EvaulateMap.getLevelStringByLevelId(userResultmap.getLevelValue());
        CalculateVO calculateVO = new CalculateVO().setScore(ans).setLevel(level);
        return  calculateVO;
    }

    // 算跑步的是2   sasda
    public CalculateVO calculate2(CalculatePO po, UserResultmap userResultmap) {
        if (userResultmap==null&&po.getResult()<EvaulateMap.getTopValueById(po.getProjectId(),po.getClassId(),po.getSex())){
            CalculateVO calculateVO = new CalculateVO().setScore(100).setLevel("优秀");
            return  calculateVO;
        }else if (userResultmap==null&&po.getResult()>EvaulateMap.getTopValueById(po.getProjectId(),po.getClassId(),po.getSex())){
            CalculateVO calculateVO = new CalculateVO().setScore(0).setLevel("不及格");
            return  calculateVO;
        }
        Double minValue = userResultmap.getMinValue();
        Double maxValue = userResultmap.getMaxValue();
        Double proDifference = userResultmap.getProDifference();
        Integer baseValue = userResultmap.getBaseValue();
        Integer bestValue = userResultmap.getBestValue();
        Integer valDifference = userResultmap.getValDifference();
        double t1=TimeCalculate(po.getResult(),minValue,po.getProjectId());
        BigDecimal bigDecimal = new BigDecimal(Double.toString(TimeCalculate(po.getResult(), minValue, po.getProjectId())));
        BigDecimal bigDecimal2 = new BigDecimal(Double.toString(proDifference));
        int t= bigDecimal.divide(bigDecimal2,ROUND_DOWN).intValue();

//        Integer tt=
        // 基础分+ 当前分与最低分距离除以成绩间距的商再乘以分间距
        Integer ans=Double.valueOf(baseValue+ t *valDifference).intValue();
        ans= ans>bestValue ? bestValue: ans;
        String level = EvaulateMap.getLevelStringByLevelId(userResultmap.getLevelValue());
        if (ans<=10){
            level="不及格";
        }
        ans= ans<10 ? 0: ans;
        CalculateVO calculateVO = new CalculateVO().setScore(ans).setLevel(level);
        return  calculateVO;
    }

    public  CalculateVO calculateAll(Integer classId,Integer sex,Integer projectId,Double result) {
        UserResultmap userResultmap = new UserResultmap();
        CalculateVO calculateVO=new CalculateVO();
        if (projectId==7){
            Integer level = evaulateMap.bmiMapper.selectLevelByValue(sex,classId,result);
            if (level==1){
                calculateVO.setScore(100).setLevel("正常");
            }else if (level==2){
                calculateVO.setScore(80).setLevel("低体重");
            }else if (level==3){
                calculateVO.setScore(80).setLevel("超重");
            }else if (level==4){
                calculateVO.setScore(60).setLevel("肥胖");
            }
        }else{
            if (projectId==2||projectId==6){
                userResultmap=evaulateMap.userResultmapMapper.selectAllByIdsRun(classId, sex,projectId, result);
                if (userResultmap==null){
                    userResultmap=evaulateMap.userResultmapMapper.selectAllByIdsRun2(classId, sex,projectId, result);
                }
                CalculatePO po = new CalculatePO(classId, sex,projectId, result);
                calculateVO=calculate2(po,userResultmap);
            }else {
                userResultmap=evaulateMap.userResultmapMapper.selectAllByIds(classId, sex,projectId, result);
                if (userResultmap==null){
                    userResultmap=evaulateMap.userResultmapMapper.selectAllByIds2(classId, sex,projectId, result);
                }
                CalculatePO po = new CalculatePO(classId, sex,projectId, result);
                calculateVO= calculate(po,userResultmap);
            }
        }
        return calculateVO;
    }


    private static Double TimeCalculate(Double result,Double minValue,Integer pId) {
        String re=result.toString();
        String min=minValue.toString();
        if (pId!=6){
            String[] resarr = re.split("\\.");
            String[] minarr = min.split("\\.");
            if (resarr[1].length()==1) resarr[1]+="0";
            if (minarr[1].length()==1) minarr[1]+="0";
            Integer min1= new Integer(minarr[0])*100+new Integer(minarr[1]);
            Integer res1= new Integer(resarr[0])*100+new Integer(resarr[1]);
            Double aDouble = new Double((min1 - res1) * 0.01);
            return  new Double((min1-res1)*0.01);
        }else {
            String[] resarr = re.split("\\.");
            String[] minarr = min.split("\\.");
            if (resarr[1].length()==1) resarr[1]+="0";
            Integer min1= new Integer(minarr[0])*60+new Integer(minarr[1]);
            Integer res1= new Integer(resarr[0])*60+new Integer(resarr[1]);
            Double aDouble = new Double((min1 - res1) * 0.01);
            return  new Double((min1-res1)*0.01);
        }
    }

    static HashMap<String,HashMap<Integer,String>> map1=new HashMap<String,HashMap<Integer,String>>();
    static HashMap<String,HashMap<Integer,String>> map2=new HashMap<String,HashMap<Integer,String>>();;

    public EvaulateMap(){
        init1();
        init2();
        init3();
        init4();
        init5();
        init6();
        init7();
    }

    private void init1() {
        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"身体快速移动能力很强。");
        test1.put(2,"身体快速移动能力较强。");
        test1.put(3,"身体快速移动能力一般。");
        test1.put(4,"身体快速移动能力较弱。");
        map1.put("run",test1);
        test2.put(1,"继续坚持锻炼，以进一步提高运动能力。");
        test2.put(2,"加强步频练习，如小步跑、高抬腿跑等；步幅练习，后蹬腿跑、车轮跑等；短距离跑，如30米、60米。");
        test2.put(3,"增加短跑难度，如上坡跑；步频练习，计时计数高抬腿；步幅练习，如后蹬腿跑、车轮跑。");
        test2.put(4,"学习正确的跑步姿势。降低短跑难度，如顺风跑、下坡跑。加强下肢肌肉力量，如深蹲、立定跳远。");
        map2.put("run",test2);
    }


    private void init2() {
        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"灵敏性、协调性、动作节奏感很好。");
        test1.put(2,"灵敏性、协调性、动作节奏感较好。");
        test1.put(3,"灵敏性、协调性、动作节奏感一般。");
        test1.put(4,"灵敏性、协调性、动作节奏感较差。");
        map1.put("jump",test1);
        test2.put(1,"继续坚持锻炼。可进一步提高跳绳速度。");
        test2.put(2,"提高跳绳速度。如定量快速连跳、定量单脚交替跳。");
        test2.put(3,"掌控跳绳的节奏感。如边跑边跳、定量快慢组合跳。");
        test2.put(4,"掌握正确的跳绳方法，另外增加下肢的弹跳力。如单/双脚垫跳，屈腿跳");
        map2.put("jump",test2);
    }

    private void init3() {
        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"心肺功能很好。");
        test1.put(2,"心肺功能较好。");
        test1.put(3,"心肺功能一般。");
        test1.put(4,"心肺功能较差。");
        map1.put("feihuo",test1);
        test2.put(1,"应继续坚持锻炼，以增强体质。");
        test2.put(2,"增加慢跑，跑楼梯等运动以进一步提高心肺功能");
        test2.put(3,"增加伸展运动、扩胸运动等以提高心肺功能。");
        test2.put(4,"掌握正确的肺活量测试方法，增加吹气球、吹乒乓球以提高心肺功能。");
        map2.put("feihuo",test2);
    }

    private void init4() {
        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"腰腹部肌肉力量和耐力很好。");
        test1.put(2,"腰腹部肌肉力量和耐力较好。");
        test1.put(3,"腰腹部肌肉力量和耐力一般。");
        test1.put(4,"腰腹部肌肉力量和耐力较差。");
        map1.put("yangwo",test1);
        test2.put(1,"应继续坚持锻炼，以增强体质。");
        test2.put(2,"控制仰卧起坐的速度和次数进行加难练习，如30秒25个仰卧起坐。");
        test2.put(3,"增加仰卧起坐的辅助练习，如仰卧举腿、平板支撑等。");
        test2.put(4,"控制仰卧起坐的手臂位置进行减难练习，如将双手放于身体两侧。");
        map2.put("yangwo",test2);
    }

    private void init5() {
        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"体型发育正常。");
        test1.put(2,"体型偏瘦。");
        test1.put(3,"体型偏胖。");
        test1.put(4,"体型肥胖。");
        map1.put("bmi",test1);
        test2.put(1,"进行规律的体育锻炼，以增强体质。");
        test2.put(2,"加强蛋白质的摄入，增加力量锻炼。");
        test2.put(3,"适当控制饮食量，增加体育锻炼。");
        test2.put(4,"减少高脂甜食饮食，适当控制饮食量，增强体育锻炼。");
        map2.put("bmi",test2);
    }

    private void init6() {
        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"耐力素质很好。");
        test1.put(2,"耐力素质较好。");
        test1.put(3,"耐力素质一般。");
        test1.put(4,"耐力素质较差。");
        map1.put("runback",test1);
        test2.put(1,"保持运动水平，适当提高运动强度，以取得更好的成绩。");
        test2.put(2,"加大步幅、加快步频和摆臂速度，如绳梯、小栏架组合。");
        test2.put(3,"加强耐力练习，如节奏跑（例：400米跑，第一次完成1´45 \"，第二次完成1´40 \"…）。");
        test2.put(4,"加强耐力和力量练习，如跑楼梯、节奏跑（例：400米跑，第一次完成2´15 \"，第二次完成2´10 \"…）等。");
        map2.put("runback",test2);
    }

    private void init7() {

        HashMap<Integer, String> test1 = new HashMap<>();
        HashMap<Integer, String> test2 = new HashMap<>();
        test1.put(1,"柔韧性（肌肉的弹性和关节的灵活性）很好。");
        test1.put(2,"柔韧性（肌肉的弹性和关节的灵活性）较好。");
        test1.put(3,"柔韧性（肌肉的弹性和关节的灵活性）一般。");
        test1.put(4,"柔韧性（肌肉的弹性和关节的灵活性）较差。");
        map1.put("qianqu",test1);
        test2.put(1,"应继续坚持锻炼，以进一步增强体质。");
        test2.put(2,"可增加各种球类运动以增强体质。");
        test2.put(0,"可尝试做横劈叉和竖叉以进一步提高柔韧性。");
        test2.put(3,"增加正（侧）压腿、跨栏坐等以提高柔韧性。");
        test2.put(4,"增加正（侧）压腿（坚持10秒）、弓步压腿等以提高柔韧性。");
        map2.put("qianqu",test2);
    }



    public  static Double getAllScore2(Integer fifity, Integer bmi, Integer vital, Integer situp, Integer jumpreult, Integer runback, Integer sitrech, Integer gradeNum){
        if (gradeNum==1||gradeNum==2){
            if ((fifity==null||bmi==null||vital==null||jumpreult==null||sitrech==null)){
                return null;
            }
        }
        if (gradeNum==3||gradeNum==4){
            if (fifity==null||bmi==null||vital==null||situp==null||jumpreult==null||sitrech==null){
                return null;
            }
        }
        if (gradeNum==5||gradeNum==6){
            if ((fifity==null||bmi==null||vital==null||situp==null||jumpreult==null||sitrech==null||runback==null)){
                return null;
            }
        }
        fifity=fifity==null ? 0 :fifity;
        bmi=bmi==null ? 0 :bmi;
        vital=vital==null ? 0 :vital;
        situp=situp==null ? 0 :situp;
        jumpreult=jumpreult==null ? 0 :jumpreult;
        runback=runback==null ? 0 :runback;
        sitrech=sitrech==null ? 0 :sitrech;
        gradeNum=gradeNum==null ? 0 :gradeNum;
        // 获得IBM等级;asdasd
        Integer other=jumpreult>=100 ? jumpreult-100:0;
        jumpreult=jumpreult>=100? 100 : jumpreult;

        if (gradeNum<=2){
            Integer t=bmi*15+vital*15+fifity*20+sitrech*30+jumpreult*20;
            double v = (bmi * 0.15 + vital * 0.15 + fifity * 0.2 + sitrech * 0.3 + jumpreult * 0.2) + other;
            v=(double) Math.round(v * 10) / 10;
            return v;
        }else if (gradeNum>2&&gradeNum<=4){

            double v = (bmi * 0.15 + vital * 0.15 + fifity * 0.2 + sitrech * 0.2 + jumpreult * 0.2+situp*0.1) + other;
            v=(double) Math.round(v * 10) / 10;
            return v;
        }else {
//            System.out.println(bmi*15+vital*15+fifity*20+sitrech*10+jumpreult*20+situp*10+runback*10);
//            return new Double((bmi*15+vital*15+fifity*20+sitrech*10+jumpreult*20+situp*10+runback*10)/100+other);
            double v = (bmi * 0.15 + vital * 0.15 + fifity * 0.2 + sitrech * 0.1 + jumpreult * 0.1+situp*0.2+runback*0.1) + other;
            v=(double) Math.round(v * 10) / 10;
            return v;
        }
    }


    public static Integer getLevel(Integer score){
        if (score==null){
            return null;
        }
        if (score>=90&&score<=120){
            return 1;
        }
        if (score>=80&&score<=89){
            return 2;
        }
        if (score>=60&&score<=79){
            return 3;
        }
        return  4;
    }


    public static String getLevelStringByScore(Integer score){
        if (score==null){
            return null;
        }
        if (score>=90&&score<=120){
            return "优秀";
        }
        if (score>=80&&score<=89){
            return "良好";
        }
        if (score>=60&&score<=79){
            return "及格";
        }
        return  "不及格";
    }

    public static String getLevelStringByLevelId(Integer levelId){
        if (levelId==null){
            return null;
        }
        if (levelId==1){
            return "优秀";
        }
        if (levelId==2){
            return "良好";
        }
        if (levelId==3){
            return "及格";
        }
        return  "不及格";
    }





    public static String getEvaulate(Integer fifity,Double bmi,Integer vital,Integer situp,Integer jumpreult,Integer runback,Integer sitrech,Integer sex,String gradeNum){
        System.out.println(map1);
        System.out.println(map2);

        // 1,2 没有仰卧起坐和50  34 年级没有50米，  仰卧和50米判断传过来的参数是否为空
//        Integer t=evaulateMap. bmiMapper.selectLevelByValue(sex, new Integer(gradeNum.substring(1, 2)), bmi);
        String s0 = bmi==null?"":map1.get("bmi").get(evaulateMap.bmiMapper.selectLevelByValue(sex, new Integer(gradeNum.substring(1, 2)), bmi));
        String s1 = vital==null?"": map1.get("feihuo").get(getLevel(vital));
        String s2 = fifity==null?"":map1.get("run").get(getLevel(fifity));
        String s3 = sitrech==null?"":map1.get("qianqu").get(getLevel(sitrech));
//        HashMap<Integer, String> qianqu= map1.get("qianqu");
//        String s3 = sex == 1 ? qianqu.get(getLevel(sitrech)): qianqu.get(0);
        String s4 = jumpreult==null?"":map1.get("jump").get(getLevel(jumpreult));
        String s5 =situp==null? "": map1.get("yangwo").get(getLevel(situp));
        String s6 =runback==null ? "":map1.get("runback").get(getLevel(runback));
        String ans=s0.concat(s1).concat(s2).concat(s3).concat(s4).concat(s5).concat(s6);
        return  ans;
    }

    public static   String getSueggest(Integer fifity,Double bmi,Integer vital,Integer situp,Integer jumpreult,Integer runback,Integer sitrech,Integer sex,String  gradeNum){
//      Integer t=  bmiMapper.selectLevelByValue(sex, new Integer(gradeNum.substring(1, 2)), bmi);
        String s0 = bmi==null?"":map2.get("bmi").get(evaulateMap. bmiMapper.selectLevelByValue(sex, new Integer(gradeNum.substring(1, 2)), bmi)).trim();
        String s1 = vital==null?"":map2.get("feihuo").get(getLevel(vital));
        String s2 = fifity==null?"":map2.get("run").get(getLevel(fifity));
        HashMap<Integer, String> qianqu= map2.get("qianqu");
        String s3="";
        if (sitrech!=null){
            s3 = sex == 1 ? qianqu.get(getLevel(sitrech)): qianqu.get(0);
        }
        String s4 = jumpreult==null?"":map2.get("jump").get(getLevel(jumpreult));
        String s5 = situp==null? "": map2.get("yangwo").get(getLevel(situp));
        String s6 = runback==null ? "":map2.get("runback").get(getLevel(runback));
        String ans=s0.concat(s1).concat(s2).concat(s3).concat(s4).concat(s5).concat(s6);
        return  ans;
    }



    // 获得最高成绩

    public  Double getMaxScore(Integer sex,String gradeId,Integer projectId){
        HashMap<Integer, List> map = maxMap.get(projectId);
        List list = map.get(sex);
        Integer integer = Integer.valueOf(gradeId);
        Object o = list.get(integer - 1);
        if (o==null) return null;
        Double ans = new Double(o.toString());
        return ans==null? null:ans;
    }




}
